package com.xxxx.yebserver.config.security;

import com.xxxx.yebserver.service.MenuService;
import com.xxxx.yebserver.service.RoleService;
import com.xxxx.yebserver.vo.MenusWithRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 权限控制，根据请求URL分析出所对应的用户组
 */
@Component
public class CustomerFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    MenuService menuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String url = ((FilterInvocation) object).getRequestUrl();
        List<MenusWithRoleVo> roles = menuService.getMenusWithRole();
        if(roles != null && roles.size() > 0){
            for (MenusWithRoleVo role : roles) {
                //判断请求url与菜单的url是否匹配，匹配则获得菜单对应的用户组
                if(antPathMatcher.match(role.getUrl(),url)){
                    String[] roleArr = role.getRoles().stream().map(item -> item.getRoleName()).toArray(String[]::new);
                    return SecurityConfig.createList(roleArr);
                }
            }
        }
        //没有匹配给定默认登录即可访问
        return SecurityConfig.createList("ROLE_login");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
